package org.filedetail;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.ds.GlobalDSFactory;
import cn.hutool.setting.Setting;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class App {

    public static void main(String[] args) {
        // (类型 名称 路径 大小 创建时间 修改时间 MD5 SHA1)
        String path = "";
        if (args.length > 0) path = args[0];

        if (args.length == 0) path = "D:/";

        StopWatch stopWatch = new StopWatch();
        //递归获取所有文件和目录
        File file = FileUtils.getFile(path);
        stopWatch.start();
        Collection<File> listFiles = FileUtils.listFilesAndDirs(file, TrueFileFilter.INSTANCE, DirectoryFileFilter.DIRECTORY);
        //Collection<File> listFiles = FileUtils.listFiles(file, null, true);
        stopWatch.stop();
        int fileCount = listFiles.size();
        System.out.println("fileCount：" + fileCount);
        double timeSeconds = stopWatch.getTotalTimeSeconds();
        System.out.printf("%.2f\n", timeSeconds);
        System.out.printf("%.2f\n", timeSeconds / 60);

        List<Entity> insertList = new LinkedList<>();
        try {
            for (File f : listFiles) {
                BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
                // 获取文件的创建时间
                Long creationTime = attr.creationTime().toMillis();
                //System.out.println("Creation Time: " + creationTime);

                Entity entity = Entity.create("ALLF");
                entity.put("TYPE", f.isFile() ? "F" : "D");
                entity.put("NAME", f.getName());
                entity.put("PATH", f.getAbsolutePath());
                entity.put("CREATE_DATE", creationTime);
                if (f.isFile()) {
                    // 获取文件的最后修改时间
                    Long lastModifiedTime = attr.lastModifiedTime().toMillis();
                    //System.out.println("Last Modified Time: " + lastModifiedTime);

                    // 调用Hutool的方法获取文件大小并转换为易读的格式
                    String readableFileSize = FileUtil.readableFileSize(f);
                    long size = FileUtil.size(f);

                    //String md5 = MD5.create().digestHex(f).toUpperCase();

                    entity.put("UPDATE_DATE", lastModifiedTime);
                    entity.put("SIZE", size);
                    entity.put("DISPLAY_SIZE", readableFileSize);
                    //entity.put("MD5", md5);
                }
                insertList.add(entity);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        String workDir = getWorkDir();
        try {
            File dbfile = FileUtils.getFile(workDir, "file-detail-recorder.db");
            Path dbpath = Paths.get(dbfile.getAbsolutePath());
            if (Files.exists(dbpath)) {
                Files.write(dbpath, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
            } else {
                Files.createFile(dbpath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String dbUrl = String.format("jdbc:sqlite:%s/file-detail-recorder.db", workDir);
        saveList(dbUrl, insertList);
    }

    public static String getWorkDir() {
        ProtectionDomain protectionDomain = App.class.getProtectionDomain();
        CodeSource codeSource = protectionDomain.getCodeSource();
        File jarFile = new File(codeSource.getLocation().getFile());
        String workDir = jarFile.getParentFile().getAbsolutePath();
        System.out.println("当前JAR包的路径是: " + workDir);
        return workDir;
    }

    public static void saveList(String dbUrl, List<Entity> insertList) {

        // 设置SQLite配置信息
        Setting setting = new Setting();
        setting.set("url", dbUrl); // 替换为你的数据库文件路径
        //setting.set("user", ""); // SQLite 通常不需要用户名
        //setting.set("password", ""); // SQLite 通常不需要密码
        setting.set("driverClassName", "org.sqlite.JDBC"); // SQLite的JDBC驱动类名

        // 创建SQLite配置对象
        DSFactory dsFactory = DSFactory.create(setting);
        GlobalDSFactory.set(dsFactory);

        //默认数据源
        Session session = Session.create();
        try {
            session.beginTransaction();//绑定

            String file = ResourceUtil.getResource("create.txt").getFile();
            String create = FileUtils.readFileToString(new File(file), "UTF-8");
            session.execute(create);

            session.insert(insertList);
            //
            session.commit();//提交事务
        } catch (Exception e) {
            session.quietRollback();//回滚
            e.printStackTrace();
        } finally {
            session.close();//关闭会话
        }

    }

}
